﻿using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ZXing;
using System.Windows.Markup;
using System.Drawing.Printing;
using System.Web;
using System.Threading;
using CardMonitor.Windows;
using Newtonsoft.Json.Linq;
using CardMonitor.Utils;
using CardMonitor.Model;
using Newtonsoft.Json;
using DotNetSpeech;
using System.Windows.Forms;
using CardMonitor.ViewModel;
using System.Drawing.Drawing2D;
using ZXing.QrCode.Internal;
using ZXing;
using ZXing.QrCode;




namespace CardMonitor.Pages
{
    /// <summary>
    /// QrPrint.xaml 的交互逻辑
    /// </summary>
    public partial class QrPrint : Page
    {
        SpVoice speech = new SpVoice();
        MainWindow mainWindow = null;
        SynchronizationContext _syncContext = null;
        string filePath = null;
        IndexViewModel viewModel;
        private String curInputTag = "mobile";
        KeyBoardWindow inputWindow = null;
        InputWindow carInputWindow = null;
        private Action<int, String> callbackAction;
        public QrPrint()
        {
            InitializeComponent();
            viewModel = new IndexViewModel();
            viewModel.index = 0;
            _syncContext = SynchronizationContext.Current;
            callbackAction += CallBackExcute;
        }
        public QrPrint(MainWindow _win)
        {
            InitializeComponent();
            _syncContext = SynchronizationContext.Current;
            viewModel = new IndexViewModel();
            viewModel.index = 0;
            callbackAction += CallBackExcute;
            mainWindow = _win;
        }
        private void TextBox_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            string index = (string)((System.Windows.Controls.TextBlock)sender).Tag;
            int v = int.Parse(index);

            _syncContext.Post(showInputWindow, v);

        }
        private void CallBackExcute(int index, string val)
        {

            for (int i = 0; i < 5; i++)
            {
                viewModel.waiPiWeighArray.Add("");
            }
            if (viewModel.index == 3)
            {
                viewModel.carNoArray02[index] = val;
                //BillModel.PiNumberList.Add(val);
                //BillModel.PiNumberList[index] = val;
                textt.Text = String.Join("", viewModel.carNoArray02);
            }

            if (viewModel.index == 1)
            {
                viewModel.waiMaoWeighArray[index] = val;
                //BillModel.PiNumberList.Add(val);
                //BillModel.PiNumberList[index] = val;
                string inputStr = String.Join("", viewModel.waiMaoWeighArray);
                textt.Text = inputStr;

            }

            if (viewModel.index == 2)
            {
                viewModel.waiPiWeighArray[index] = val;
                string inputStr = String.Join("", viewModel.waiPiWeighArray);
                textt.Text = inputStr;

            }
        }

        private void showInputWindow(object obj)
        {
            int index = (int)obj;
            viewModel.index = index;
            if (index == 1 || index == 2)
            {
                if (carInputWindow != null)
                {
                    carInputWindow.Hide();
                }

                if (inputWindow == null)
                {
                    inputWindow = new KeyBoardWindow(callbackAction);
                    inputWindow.Owner = mainWindow;
                    inputWindow.Width = mainWindow.Width;
                    inputWindow.Left = mainWindow.Left;
                    inputWindow.Top = SystemParameters.PrimaryScreenHeight - inputWindow.Height;
                }
                inputWindow.maxLength = 7;
                inputWindow.getFlag("2");

                if (index == 2)
                {
                    inputWindow.viewModel.carNoArray.Clear();
                    foreach (String v in viewModel.waiPiWeighArray)
                    {
                        if (v != "")
                        {
                            inputWindow.viewModel.carNoArray.Add(v);
                        }

                    }
                }
                else if (index == 1)
                {
                    inputWindow.viewModel.carNoArray.Clear();
                    foreach (String v in viewModel.waiMaoWeighArray)
                    {
                        if (v != "")
                        {
                            inputWindow.viewModel.carNoArray.Add(v);
                        }

                    }
                }
                inputWindow.showKeys(3);
                inputWindow.Show();
            }
            else if (index == 3)
            {
                if (inputWindow != null)
                {
                    inputWindow.Hide();
                }
                if (carInputWindow == null)
                {
                    carInputWindow = new InputWindow(callbackAction);
                    carInputWindow.Owner = mainWindow;
                    carInputWindow.Width = mainWindow.Width;
                    carInputWindow.Left = mainWindow.Left;
                    carInputWindow.Top = SystemParameters.PrimaryScreenHeight - carInputWindow.Height;
                }
                carInputWindow.maxLength = 7;
                carInputWindow.viewModel.carNoArray.Clear();
                foreach (String v in viewModel.carNoArray02)
                {
                    if (v != "")
                    {
                        carInputWindow.viewModel.carNoArray.Add(v);
                    }

                }
                if (carInputWindow.viewModel.carNoArray.Count == 0)
                {
                    carInputWindow.showKeys(1);
                }
                else
                {
                    carInputWindow.showKeys(2);
                }
                carInputWindow.Show();
            }
            else
            {
                if (inputWindow != null && inputWindow.IsActive)
                {
                    inputWindow.Hide();
                }
                if (carInputWindow != null && carInputWindow.IsActive)
                {
                    carInputWindow.Hide();
                }
            }
        }
        private String getNumField(String val, String inputVal)
        {
            if (inputVal == "消除")
            {
                return "";
            }
            if (inputVal == "." && curInputTag == "mobile")
            {
                return val;
            }
            if (inputVal == "." && "".Equals(val))
            {
                return val;
            }
            if (inputVal == "." && val.IndexOf(".") >= 0)
            {
                return val;
            }

            if (curInputTag == "mobile" && val.Length >= 11)
            {
                return val;
            }

            if ((curInputTag == "wp" || curInputTag == "wm") && val.IndexOf(".") >= 0)
            {
                if (val.IndexOf(".") + 3 == val.Length) return val;
            }
            if ((curInputTag == "wp" || curInputTag == "wm") && !"".Equals(val))
            {
                if (double.Parse(val + inputVal) > 99.99) return val;
            }

            String value = val;

            value = val + inputVal;

            return value;
        }


        private void inputText(String val)
        {
            String value = "";
            //if (curInputTag == "wp")
            //{
            //    value = this.wpText.Text;
            //}
            //else if (curInputTag == "wm")
            //{
            //    value = this.wmText.Text;
            //}

            if (curInputTag == "mobile")
            {
                //  value = this.mobileText.Text;
            }

            String value2 = "";
            if ("-1".Equals(val))
            {
                if (value.Length > 0)
                {
                    value2 = value.Substring(0, value.Length - 1);
                }
            }
            else
            {
                value2 = getNumField(value, val);
            }


            if (curInputTag == "mobile")
            {
                // this.mobileText.Text = value2;
            }
        }
        public void MMPage_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            string val = getKeyValue(e.Key);
            if ("back".Equals(val))
            {
                inputText("-1");
            }
            else if ("point".Equals(val))
            {
                inputText(".");
            }
            else
            {
                if (e.Key.ToString().StartsWith("D"))
                {
                    inputText(val);
                }
            }
            //MessageBox.Show(e.Key.ToString());
            e.Handled = true;
        }
        private string getKeyValue(Key key)
        {
            string KeyValue = "-1";

            switch (key)
            {
                case Key.D1:
                    KeyValue = "1";
                    break;
                case Key.D2:
                    KeyValue = "2";
                    break;
                case Key.D3:
                    KeyValue = "3";
                    break;
                case Key.D4:
                    KeyValue = "4";
                    break;
                case Key.D5:
                    KeyValue = "5";
                    break;
                case Key.D6:
                    KeyValue = "6";
                    break;
                case Key.D7:
                    KeyValue = "7";
                    break;
                case Key.D8:
                    KeyValue = "8";
                    break;
                case Key.D9:
                    KeyValue = "9";
                    break;
                case Key.D0:
                    KeyValue = "0";
                    break;
                case Key.OemPeriod:
                    KeyValue = "point";
                    break;
                case Key.Back:
                    KeyValue = "back";
                    break;
                case Key.Enter:
                    KeyValue = "enter";
                    break;
            }
            return KeyValue;
        }

        private void print(object sender, RoutedEventArgs e)
        {
            string code = textt.Text;//Qr.Text输入框内容
            GenerateQRCode(code);
            if (null != inputWindow)
            {
                inputWindow.Hide();
            }
        }
        private void GenerateQRCode(string code)
        {
            if ("" == code)
            {
                speech.Speak("请输入验证码", SpeechVoiceSpeakFlags.SVSFlagsAsync);
                showMessage("请输入验证码");
            }
            else
            {
                JObject paramJSON = new JObject();
                paramJSON.Add("verificationCode", code);
                HttpPostWindow httpPostWindow = new HttpPostWindow();
                httpPostWindow.Owner = mainWindow;

                httpPostWindow.setParamObject(paramJSON);
                String response = HttpPostHelper.doHttpPost("/qd-s-factory/makeCard/getBillInfoNew", paramJSON.ToString());
                JObject respJson = JObject.Parse(response);
                string status = respJson["code"].ToString();
                JObject newJson = new JObject();
                if (status.ToLower() == "00000")
                {
                    var jsonStr = respJson["data"].ToString();
                    List<BillModel> bills = JsonConvert.DeserializeObject<List<BillModel>>(jsonStr);
                    Thread.Sleep(1000);
                    if (bills.Count == 1)//查询到的数量为1进行打印
                    {

                        string ID = bills[0].Id.ToString();//单据号码
                        var barcodeWriter = new BarcodeWriter
                        {
                            Format = BarcodeFormat.QR_CODE,
                            Options = new ZXing.Common.EncodingOptions
                            {
                                //Width = 300,
                                //Height = 300,
                                //Margin = 1
                                //ErrorCorrection = ErrorCorrectionLevel.H,
                                Width = 200,
                                Height = 200,
                                Margin = 1,
                                 Hints =
        {
            [EncodeHintType.ERROR_CORRECTION] = ErrorCorrectionLevel.H  // 关键修改
        }
                            }
                        };

                        using (System.Drawing.Bitmap bitmap = barcodeWriter.Write(ID))
                        {

                            string filePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "QR.png");
                            bitmap.Save(filePath, ImageFormat.Png);
                            BitmapImage bitmapImage = new BitmapImage();
                            using (var ms = new MemoryStream())
                            {
                                bitmap.Save(ms, ImageFormat.Png);
                                ms.Seek(0, SeekOrigin.Begin);
                                bitmapImage.BeginInit();
                                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                                bitmapImage.StreamSource = ms;
                                bitmapImage.EndInit();
                            }
                            //  QRCodeImage.Source = bitmapImage;二维码展示

                            PrintDocument pd = new PrintDocument();
                            pd.PrintPage += (sender, args) =>
                            {
                                using (var image = System.Drawing.Image.FromFile(filePath))
                                {
                                    System.Drawing.Point p = new System.Drawing.Point(100, 100);
                                    args.Graphics.DrawImage(image, 10, 10, image.Width, image.Height);
                                } // Image is disposed here
                            };
                            showMessage("打印中");
                            //qRPrint.Show();
                            pd.Print(); // 打印

                            // File lock should be released after the PrintPage event handler completes
                            this.NavigationService.GoBack();
                        }
                    }
                    else if (bills.Count == 0)//0未查询到，验证码输入错误。
                    {

                        speech.Speak("未查询到单据，请检查验证码是否正确", SpeechVoiceSpeakFlags.SVSFlagsAsync);
                        showMessage("未查询到单据，请检查验证码是否正确");
                    }
                    else
                    {
                        showMessage("系统执行出错");
                    }
                }
                else
                {
                    showMessage("系统执行出错");
                }
            }






        }






        private void Qr_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void goIndex(object sender, RoutedEventArgs e)
        {
            if (null != inputWindow)
            {
                inputWindow.Hide();
            }

            this.NavigationService.GoBack();
        }
        private void showMessage(String message)
        {
            InfoWindow infoWindow = new InfoWindow(message);
            infoWindow.Owner = mainWindow;
            infoWindow.ShowDialog();
        }
    }

    //    string filePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "QRCo.png");
    //    bitmap.Save(filePath, ImageFormat.Png);
    //    // Convert Bitmap to BitmapImage for WPF
    //    BitmapImage bitmapImage = new BitmapImage();
    //    using (var ms = new MemoryStream())
    //    {
    //        bitmap.Save(ms, ImageFormat.Png);
    //        ms.Seek(0, SeekOrigin.Begin);
    //        bitmapImage.BeginInit();
    //        bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
    //        bitmapImage.StreamSource = ms;
    //        bitmapImage.EndInit();
    //    }

    //    // Assuming you have an Image control named `QRCodeImage` in your XAML
    //    QRCodeImage.Source = bitmapImage;

    //    PrintDocument pd = new PrintDocument();
    //    pd.PrintPage += (sender, args) =>
    //    {
    //        System.Drawing.Image i = System.Drawing.Image.FromFile(filePath);
    //        System.Drawing.Point p = new System.Drawing.Point(100, 100);
    //        args.Graphics.DrawImage(i, 10, 10, i.Width, i.Height);
    //        args.Graphics.DrawImage(i, 10, 10, i.Width, i.Height);
    //    };
    //    pd.Print();//打印
    //    this.NavigationService.GoBack();
    //}
}
